import config
import time
from dateutil import rrule
from datetime import datetime
from utils import *


def register():
	return CET46CountdownQuery()


class CET46CountdownQuery:
	def __init__(self):
		self.type = 'passive'
		self.help = \
'''四六级倒计时查询：
	用法：*四六级倒计时
	查询距离下一次四六级笔试的天数。'''

	def calc(self):
		date = datetime.now()
		until = datetime(date.year, 6, 1)
		until = datetime(date.year, 6, 14 - until.isoweekday() % 7)
		days = rrule.rrule(freq=rrule.DAILY, dtstart=date, until=until)

		if days.count() <= 0 and \
				(date.year != until.year \
				 or date.month != until.month \
				 or date.day != until.day):
			until = datetime(date.year + 1, 6, 7)
			days = rrule.rrule(freq=rrule.DAILY, dtstart=date, until=until)

		return days.count()

	def run(self, gum, msg):
		if not msg['type'] in ['FriendMessage', 'GroupMessage'] \
				or len(msg['messageChain']) <= 1 \
				or msg['messageChain'][1]['type'] != 'Plain' \
				or msg['messageChain'][1]['text'].split()[0] != '*四六级倒计时':
			return

		chain = MsgChain()
		chain.addPlain(f'糖糖提醒您，距离四六级还有{self.calc()}天。数据仅供参考，如有变动请参考相关通知。')

		autoReply(chain, gum)